// src/hooks/useVehicleList.ts
import { ref } from 'vue'
import { VehicleApi } from '@/api/oa/vehicle'

export interface VehicleItem {
  id: number
  vehicleName: string
  licensePlate: string
}

export const useVehicleList = () => {
  const vehicleList = ref<VehicleItem[]>([])

  // 获取车辆列表
  const loadVehicleList = async () => {
    try {
      const res = await VehicleApi.getVehiclePage({})
      if (res?.list?.length) {
        vehicleList.value = res.list.map((item) => ({
          id: item.id,
          vehicleName: item.name || '未知车辆',
          licensePlate: item.plateNumber || '未知车牌'
        }))
      }
    } catch (error) {
      console.error('获取车辆列表失败', error)
    }
  }

  // 根据 vehicleName 设置 licensePlate
  const updateLicensePlate = (
    vehicleName: string | undefined,
    licensePlateRef: Ref<string | undefined>
  ) => {
    const selectedVehicle = vehicleList.value.find(
      (v) => v.vehicleName === vehicleName
    )
    licensePlateRef.value = selectedVehicle?.licensePlate || undefined
  }

  return {
    vehicleList,
    loadVehicleList,
    updateLicensePlate
  }
}
